package cpumassager

import (
	"errors"
	"time"

	"github.com/shirou/gopsutil/cpu"
)

// ICPUCollector 收集CPU使用率的接口
type ICPUCollector interface {
	// GetCPUsage 获取CPU使用率
	GetCPUsage() float64
}

type SysCPUCollector struct {
	period     time.Duration
	curCPUData float64
}

func (c *SysCPUCollector) GetCPUsage() float64 {
	curCPUData, _ := cpu.Percent(c.period, false)
	c.curCPUData = curCPUData[0]
	return c.curCPUData
}

// NewSysCPUsageCollector 新建一个系统CPU使用率收集器
func NewSysCPUsageCollector(period time.Duration) (ICPUCollector, error) {
	if period.Seconds() < 0.05 {
		return nil, errors.New("the sampling period is too short")
	}
	_, err := cpu.Info()
	if err != nil {
		return nil, err
	}
	c := &SysCPUCollector{period: period}
	curSysCPUData, err := cpu.Percent(c.period, false)
	if err != nil {
		return nil, err
	}
	c.curCPUData = curSysCPUData[0]
	return c, nil
}
